package com.meng.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;


/**
 * Created by MENG on 2017/2/14.
 */
public class Utils
{
	public static volatile long startTime = 0;

	public static volatile long endTime = 0;

	/**
	 *
	 * MD5 加密
	 *
	 * @param str 加密前的字符串
	 * @return newStr 加密后的字符串
	 * @throws NoSuchAlgorithmException
	 */
	public static String encodeByMd5(String str) throws NoSuchAlgorithmException
	{
		String newStr = "";
		try
		{
			MessageDigest md = null;

			md = MessageDigest.getInstance("MD5");

			md.update(str.getBytes());

			newStr = new BigInteger(1, md.digest()).toString(16);
		}
		catch (NoSuchAlgorithmException e)
		{
			throw new NoSuchAlgorithmException("MD5密码加密出错", e);
		}

		return newStr;
	}

	/**
	 *
	 * 读取email.properties配置文件
	 *
	 * @param key 配置文件中的key
	 * @param propertiesName 配置文件名称
	 * @return
	 * @throws IOException
	 */
	public static String getPropertiesValByKey(String key, String propertiesName) throws
		IOException
	{
		InputStream inStream = Utils.class.getClassLoader().getResourceAsStream(propertiesName);

		Properties prop = new Properties();

		try
		{
			prop.load(new InputStreamReader(inStream, "UTF-8"));
		}
		catch (IOException e)
		{
			throw new IOException("加载配置文件路径出错->>" + propertiesName,e);
		}

		String value = prop.getProperty(key);

		return value;
	}

	/**
	 *
	 * 获取netty-config.properties配置文件中的值
	 *
	 * @param key
	 * @return val
	 * @throws IOException
	 */
	public static String getNettyPropsValByKey(String key) throws IOException
	{
		return getPropertiesValByKey(key,"netty-config.properties");
	}

	/**
	 * 格式化日期
	 *
	 * @param format 	格式
	 * @param date		日期
     * @return
     */
	public static String getDateFormat(String format, Date date)
	{
		if(date == null)
		{
			date = new Date();
		}

		if(format == null || format.length() == 0)
		{
			format = "yyyy-MM-dd";
		}

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);

		return simpleDateFormat.format(date);
	}

	/**
	 * 获取当前日期格式化字符
	 *
	 * @param format 	格式
	 * @return
	 */
	public static String getDateFormat(String format)
	{
		if(format == null || format.length() == 0)
		{
			format = "yyyy-MM-dd";
		}

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);

		return simpleDateFormat.format(new Date());
	}
}
